package com.mm.service;

import com.mm.domain.SecurityUser;
import com.mm.domain.User;
import com.mm.feign.UserFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;

@Component
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userFeign.findByName(username);
        if(user == null){
            throw new UsernameNotFoundException("UserName " + username + " not found");
        }

        boolean accountNonExpired = true;      //账户是否未过期(true:未过期,false:过期)
        boolean accountNonLocked = true;       //账户是否未锁定(true:未锁定,false:锁定)
        boolean credentialsNonExpired = true;  //凭证是否未过期(true:未过期,false:过期)
        boolean enabled = true;                //是否可用(true:可用,false:不可用)
        Set<GrantedAuthority> authorities = new HashSet<>();  //用户权限
        String roleNames = user.getRoleNames();
        if(StringUtils.isNotEmpty(roleNames)){
            String [] roleNameArr = roleNames.split(",");
            for(String roleName : roleNameArr){
                authorities.add(new SimpleGrantedAuthority(roleName));
            }
        }
        //这里返回自定义安全用户,也可用默认的org.springframework.security.core.userdetails.User
        return new SecurityUser(username,new BCryptPasswordEncoder().encode(user.getPassword()),authorities,accountNonExpired,accountNonLocked,credentialsNonExpired,enabled);
    }
}
